const Answer = require('../models/answers')
const Comment = require('../models/comments')

class AnswerController {
  // =================检查回答是否存在==========
  async checkAnswerExist(ctx, next) {
    // 回答的id
    const answer  = await Answer.findById(ctx.params.answerId);
    if (!answer) {
      ctx.throw(404, '回答不存在！')
    }
    // 问题的id
    // if (answer.questionId !== ctx.params.questionId) {
    //   ctx.throw(404, '该问题下没有此回答')
    // }
    // 保存到state，用于校验当前回答是否属于登陆用户
    ctx.state.answer = answer
    await next()
  }
  // ================检查回答是否属于登陆者============
  async checkAnswerOwner(ctx, next) {
    const { answer } = ctx.state
    if (answer.author.toString() !== ctx.state.user.userId) {
      ctx.throw(403, '没有权限操作此回答')
    }
    await next()
  }

  // =================创建回答=================
  async createAnswer(ctx) {
    ctx.verifyParams({
      content: {type: 'string', required: true},
    })

    // 回答者id
    const author = ctx.state.user.userId
    // 问题id
    const { questionId } = ctx.params
    const answer  = await Answer({...ctx.request.body, author,questionId}).save()

    ctx.body = answer
  }

  // =================搜索回答=================
  async seachAnswer(ctx) {
    // 分页逻辑
    let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
    // 防止输入负数
    perPage = Math.max(perPage * 1, 1) 
    page = Math.max(page * 1,1) 
    
    // 文章内容中搜索关键词
    const q = new RegExp(ctx.query.q)

    const answerList = await Answer.find({content: q, questionId: ctx.params.questionId}).limit(perPage).skip((page-1) * perPage)  // limit限制查询数量、skip跳过多少条记录

    ctx.body = answerList
  }

  // ==================获取回答列表==================
  async getAnswerList(ctx) {
    // 分页逻辑
    let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
    // 防止输入负数
    perPage = Math.max(perPage * 1, 1) 
    page = Math.max(page * 1,1) 

    // 获取回答列表数据
    const answerList = await Answer.find().limit(perPage).skip((page-1) * perPage).populate('author questionId')
    
    // 返回结果
    ctx.body = {
      message: '请求成功',
      data: answerList
    }
    
  }

  // =================获取特定答案=============
  async getAnswer(ctx) {
    // 显示额外的字符串
    const fields = ctx.query.fields || ''
    const selectFields = fields.split(';').filter(item=>item).map(item=> ' +'+item).join('')
    // 回答的id
    const answer = await Answer.findById(ctx.params.answerId).select(selectFields)
    ctx.body = answer
  }

  // =================更新回答=================
  async updateAnswer(ctx) {
    ctx.verifyParams({
      content: {type: 'string', required: true},
    })
    const answer  = await Answer.findByIdAndUpdate(ctx.params.answerId, ctx.request.body,{new: true})
    // 返回更新结果
    ctx.body = answer
  }
  // =================删除回答=================
  async deleteAnswer(ctx) {
    await Answer.findByIdAndRemove(ctx.params.answerId)
    ctx.status = 204
  }

}

module.exports = new AnswerController()